<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>单位管理</title>

    <link rel="shortcut icon" href="favicon.ico">
    <link href="css/bootstrap.min.css?" rel="stylesheet">
    <link href="css/font-awesome.css?" rel="stylesheet">

    <!-- jqgrid-->
    <link href="css/plugins/jqgrid/ui.jqgrid.css" rel="stylesheet">

    <link href="css/animate.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        /* Additional style to fix warning dialog position */
        #alertmod_table_list_2 {
            top: 900px !important;
        }
    </style>
</head>
<body>
<div class="wrapper wrapper-content  animated fadeInRight">
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox ">
                <div class="ibox-title">
                    <h5>jQuery Grid Plugin – jqGrid</h5>
                </div>
                <div class="ibox-content" style="color: #1f90d8">
                    <p>单位列表</p>
                    <div class="jqGrid_wrapper">
                        <table id="table_list_2">
                            <thead>
                            <tr>
                                <th>序号</th>
                                <th>单位名</th>
                            </tr>
                            </thead>
                            <tbody id="alertmod_table_list_2">
                            <!-- 使用Thymeleaf迭代数据 -->
                            <tr th:each="unit : ${data}">
                                <td th:text="${unit.unit_id}"></td>
                                <td th:text="${unit.unit_name}"></td>
                            </tr>
                            </tbody>
                        </table>
                        <div id="pager_list_2"></div>
                    </div>
                    <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#addUnitModal">添加单位</button>
                    <button class="btn btn-success btn-lg" onclick="refreshData()">获取单位</button>
                    <button class="btn btn-warning btn-lg" onclick="editSelectedUnit()">修改单位</button>
                    <button class="btn btn-danger btn-lg" onclick="deleteSelectedUnit()">删除单位</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="addUnitModal" tabindex="-1" role="dialog" aria-labelledby="addUnitModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addUnitModalLabel">新增单位</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <!-- 用户信息表单 -->
                    <form id="addGameForm">
                        <div class="form-group">
                            <label for="unit_name">单位名</label>
                            <input type="text" class="form-control" id="unit_name" name="unit_name" required>
                        </div>
                        <button type="button" class="btn btn-primary" onclick="addUnit()">提交</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="editUnitModal" tabindex="-1" role="dialog" aria-labelledby="editUnitModalLabel" aria-hidden="true">
        <!-- 模态框内容 -->
    </div>

</div>
<!-- 全局js -->
<script src="js/jquery.min.js?"></script>
<script src="js/bootstrap.min.js"></script>
<!-- Peity -->
<script src="js/plugins/peity/jquery.peity.min.js"></script>
<!-- jqGrid -->
<script src="js/plugins/jqgrid/i18n/grid.locale-cn.js"></script>
<script src="js/plugins/jqgrid/jquery.jqGrid.min.js"></script>
<!-- 自定义js -->
<script src="js/content.js?"></script>
<!-- Page-Level Scripts -->
<script>
    $(document).ready(function () {
        $.jgrid.defaults.styleUI = 'Bootstrap';
        // 初始化jqGrid的函数
        function initJqGrid(data) {
            $("#table_list_2").jqGrid({
                datatype: "local",
                data: data,
                height: 450,
                autowidth: true,
                shrinkToFit: true,
                rowNum: 20,
                rowList: [10, 20, 30],
                colNames: ['序号', '单位名'],
                colModel: [
                    { name: "unit_id", index: "unit_id", editable: true, width: 60, sorttype: "int", search: true },
                    { name: "unit_name", index: "unit_name", editable: true, width: 60, sorttype: "string", search: true },
                ],
                pager: "#pager_list_2",
                viewrecords: true,
                caption: "单位",
                add: true,
                edit: true,
                addtext: 'Add',
                edittext: 'Edit',
                hidegrid: false
            });
            // Add selection
            $("#table_list_2").setSelection(4, true);
            // Setup buttons
            $("#table_list_2").jqGrid('navGrid', '#pager_list_2', {
                edit: true,
                add: true,
                del: true,
                search: true
            }, {
                height: 200,
                reloadAfterSubmit: true
            });
        }
        // 使用AJAX请求从后端获取数据
        $.ajax({
            url: '/getAllUnit',
            method: 'GET',
            dataType: 'json',
            success: function (data) {
                // 初始化jqGrid
                initJqGrid(data);
            },
            error: function (error) {
                console.error('Error fetching data from the server:', error);
            }
        });
    });
    function addUnit() {
        // 获取表单数据
        var UnitData = {
            unit_name: $("#unit_name").val(),
        };
        // 发送数据到后端
        $.ajax({
            url: '/addUnit',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(UnitData),
            success: function (response) {
                // 处理成功响应，可以根据需要刷新用户列表等操作
                console.log(response);
            },
            error: function (error) {
                console.error('Error adding user:', error);
            }
        });

        // 关闭模态框
        $('#addUnitModal').modal('hide');
    }

    // 刷新数据函数
    function refreshData() {
        // 使用AJAX请求从后端获取数据
        $.ajax({
            url: '/getAllGame',
            method: 'GET',
            dataType: 'json',
            success: function (data) {
                // 清空表格数据
                $("#table_list_2").jqGrid('clearGridData');
                // 添加新数据
                for (var i = 0; i < data.length; i++) {
                    $("#table_list_2").jqGrid('addRowData', i + 1, data[i]);
                }
                console.log('Data refreshed successfully.');
            },
            error: function (error) {
                console.error('Error fetching data from the server:', error);
            }
        });
    }
    function editSelectedUnit() {
        // 获取所选行的ID
        var selectedRowId = $("#table_list_2").jqGrid('getGridParam', 'selrow');

        if (!selectedRowId) {
            alert('请先选择要编辑的游戏。');
            return;
        }

        // 获取所选行的数据
        var selectedUnitData = $("#table_list_2").jqGrid('getRowData', selectedRowId);

        // 打开编辑模态框
        openEditUnitModal(selectedUnitData);
    }

    function openEditUnitModal(UnitData) {
        // 填充模态框内容
        var modalContent = '<div class="modal-dialog" role="document">';
        modalContent += '<div class="modal-content">';
        modalContent += '<div class="modal-header">';
        modalContent += '<h5 class="modal-title" id="editUnitModalLabel">编辑单位</h5>';
        modalContent += '<button type="button" class="close" data-dismiss="modal" aria-label="Close">';
        modalContent += '<span aria-hidden="true">&times;</span>';
        modalContent += '</button>';
        modalContent += '</div>';
        modalContent += '<div class="modal-body">';
        modalContent += '<!-- 用户信息表单 -->';
        modalContent += '<form id="editUnitForm">';
        modalContent += '<div class="form-group">';
        modalContent += '<label for="editUnitId">序号</label>';
        modalContent += '<input type="text" class="form-control" id="editUnitId" name="unit_id" value="' + UnitData.unit_id + '" required>';
        modalContent += '</div>';
        modalContent += '<div class="form-group">';
        modalContent += '<label for="editUnitName">单位名</label>';
        modalContent += '<input type="text" class="form-control" id="editUnitName" name="unit_name" value="' + UnitData.unit_name + '" required>';
        modalContent += '</div>';

        modalContent += '<button type="button" class="btn btn-primary" onclick="saveEditedUnit()">保存</button>';
        modalContent += '</form>';
        modalContent += '</div>';
        modalContent += '</div>';
        modalContent += '</div>';
        modalContent += '</div>';
        // 将模态框内容添加到模态框中
        $("#editUnitModal").html(modalContent);

        // 打开模态框
        $('#editUnitModal').modal('show');
    }

    // 保存编辑后的用户函数
    function saveEditedUnit() {
        console.log('点击保存按钮。'); // 为了调试添加这一行

        // 获取表单数据
        var editedUserData = {
            game_name: $("#editUnitId").val(),
            game_icon: $("#editUnitName").val(),
        };
        // 发送数据到后端
        $.ajax({
            url: '/editUnit',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(editedUnitData),
            success: function (response) {
                // 处理成功响应，可以根据需要刷新用户列表等操作
                console.log(response);
                // 关闭模态框
                $('#editUnitModal').modal('hide');
                // 刷新数据
                refreshData();
            },
            error: function (error) {
                console.error('Error editing user:', error);
                // 输出服务器返回的错误消息
                console.error('Server error message:', error.responseText);
            }
        });


    }
    function deleteSelectedUnit() {
// 获取所选行的ID
        var selectedRowId = $("#table_list_2").jqGrid('getGridParam', 'selrow');

        if (!selectedRowId) {
            alert('请选择要删除的单位。');
            return;
        }

// 获取所选行的数据
        var selectedUnitData = $("#table_list_2").jqGrid('getRowData', selectedRowId);

// 弹出确认对话框
        var unitDelete = confirm('是否删除游戏 ' + selectedUnitData.unit_id + '？');
        if (!unitDelete) {
            return;
        }

// 发送数据到后端进行删除
        $.ajax({
            url: '/deleteUnit',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ unit_name: selectedUnitData.unit_name }),
            success: function (response) {
// 处理成功响应，可以根据需要刷新用户列表等操作
                console.log(response);
// 刷新数据
                refreshData();
            },
            error: function (error) {
                console.error('Error deleting user:', error);
// 输出服务器返回的错误消息
                console.error('Server error message:', error.responseText);
            }
        });
    }
</script>

</body>
</html>